<?php

namespace app\common\model;

use fast\DateFormat;
use think\Model;


class Semester extends Model
{
    //数据库
    protected $connection = 'database';
    // 表名
    protected $name = 'semester';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
    ];

    protected static function init()
    {
        self::beforeWrite(function ($row) {
            $start_date = strtotime($row->start_date);
            $end_date = strtotime($row->end_date);
            $row['week_nums'] = floor(abs(($start_date - (strftime("%u", $start_date) - 1) * 86400) - ($end_date - (strftime("%u", $end_date) - 1) * 86400)) / (24 * 60 * 60 * 7)) + 1;
        });
    }

    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function school()
    {
        return $this->belongsTo('School', 'school_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function getWeekList($start_time, $end_time)
    {
        $list = [];
        $weeks = DateFormat::getWeeks($start_time, $end_time);
        foreach ($weeks as $key => $week) {
            $list[] = [
                'id' => $key + 1,
                'name' => "第" . ($key + 1) . "周（{$week['range']}）"
            ];
        }

        return $list;
    }

}
